package com.dragon.codefx.config;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

/**
 * 系统托盘管理器 - SpringBoot Bean版本
 * 使用Spring的依赖注入和生命周期管理
 *
 * @author lsc
 * @since 2025/9/25
 */
@Component
public class SystemTrayManager {

    private SystemTray systemTray;
    private TrayIcon trayIcon;
    /**
     * -- SETTER --
     * 设置主舞台引用
     */
    @Setter
    private Stage primaryStage;
    private JPopupMenu popupMenu;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 初始化系统托盘
     */
    @PostConstruct
    public void initSystemTray() {
        // 检查系统是否支持托盘
        if (!SystemTray.isSupported()) {
            return;
        }
        try {
            // 设置系统属性
            System.setProperty("java.awt.headless", "false");
            // 获取系统托盘
            systemTray = SystemTray.getSystemTray();
            // 加载托盘图标
            Image trayImage = loadTrayIcon();

            // 创建托盘图标
            trayIcon = new TrayIcon(trayImage, "代码生成器");
            trayIcon.setImageAutoSize(true);
            // 创建Swing弹出菜单
            createSwingPopupMenu();
            // 添加鼠标监听器
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        // 左键单击显示窗口
                        Platform.runLater(() -> showMainWindow());
                    } else if (e.getButton() == MouseEvent.BUTTON3) {
                        // 右键显示菜单
                        showPopupMenu(e);
                    }
                }
            });
            // 将托盘图标添加到系统托盘
            systemTray.add(trayIcon);

        } catch (AWTException e) {
            System.err.println("无法添加托盘图标: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("托盘初始化出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 加载托盘图标
     */
    private Image loadTrayIcon() {
        try {
            InputStream iconStream = SystemTrayManager.class.getResourceAsStream("/icons/app-icon.png");
            if (iconStream != null) {
                BufferedImage image = ImageIO.read(iconStream);
                return image.getScaledInstance(16, 16, Image.SCALE_SMOOTH);
            }
        } catch (IOException e) {
            System.err.println("无法加载图标文件: " + e.getMessage());
        }

        return createDefaultIcon();
    }

    /**
     * 创建默认图标
     */
    private Image createDefaultIcon() {
        BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(new Color(33, 150, 243));
        g2d.fillOval(2, 2, 12, 12);
        g2d.setColor(Color.WHITE);
        g2d.setStroke(new BasicStroke(1.5f));
        g2d.drawOval(2, 2, 12, 12);

        g2d.dispose();
        return image;
    }

    /**
     * 创建Swing弹出菜单
     */
    private void createSwingPopupMenu() {
        popupMenu = new JPopupMenu();
        // 设置菜单字体（避免使用特殊字体名称）
        Font menuFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
        // 显示窗口
        JMenuItem showItem = new JMenuItem("显示窗口");
        showItem.setFont(menuFont);
        showItem.addActionListener(e -> Platform.runLater(() -> showMainWindow()));
        popupMenu.add(showItem);
        // 分隔符
        popupMenu.addSeparator();
        // 关于
        JMenuItem aboutItem = new JMenuItem("关于");
        aboutItem.setFont(menuFont);
        aboutItem.addActionListener(e -> showAboutDialog());
        popupMenu.add(aboutItem);
        // 分隔符
        popupMenu.addSeparator();
        // 退出
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.setFont(menuFont);
        exitItem.addActionListener(e -> {
            try {
                // 使用懒加载获取ApplicationExitService，避免循环依赖
                Object exitService = applicationContext.getBean("applicationExitService");
                // 使用反射调用exitApplication方法
                exitService.getClass().getMethod("exitApplication").invoke(exitService);
            } catch (Exception ex) {
                System.err.println("使用退出服务失败，使用备用退出: " + ex.getMessage());
                fallbackExit();
            }
        });
        popupMenu.add(exitItem);
    }

    /**
     * 显示弹出菜单
     */
    private void showPopupMenu(MouseEvent e) {
        SwingUtilities.invokeLater(() -> {
            // 创建一个临时的不可见组件作为菜单的父组件
            JWindow tempWindow = new JWindow();
            tempWindow.setSize(0, 0);
            tempWindow.setLocation(e.getXOnScreen(), e.getYOnScreen());
            tempWindow.setVisible(true);

            popupMenu.setInvoker(tempWindow);
            popupMenu.setLocation(e.getXOnScreen(), e.getYOnScreen());
            popupMenu.setVisible(true);

            // 当菜单隐藏时，也隐藏临时窗口
            popupMenu.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent e) {
                }

                @Override
                public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent e) {
                    tempWindow.dispose();
                }

                @Override
                public void popupMenuCanceled(javax.swing.event.PopupMenuEvent e) {
                    tempWindow.dispose();
                }
            });
        });
    }

    /**
     * 显示主窗口
     */
    private void showMainWindow() {
        if (primaryStage != null) {
            if (primaryStage.isIconified()) {
                primaryStage.setIconified(false);
            }
            primaryStage.show();
            primaryStage.toFront();
            primaryStage.requestFocus();
        }
    }

    /**
     * 隐藏到托盘
     */
    public void hideToTray() {
        try {
            if (primaryStage != null) {
                primaryStage.hide();
                // 显示托盘提示
                if (trayIcon != null) {
                    System.out.println("显示托盘消息");
                    trayIcon.displayMessage(
                        "JavaFX Demo",
                        "应用程序已最小化到系统托盘",
                        TrayIcon.MessageType.INFO
                    );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示关于对话框
     */
    private void showAboutDialog() {
        Platform.runLater(() -> {
            try {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("关于");
                alert.setHeaderText("代码生成器");
                alert.setContentText("版本: 1.0\n作者: dragon\n描述: 一个支持系统托盘的JavaFX演示应用程序");
                alert.showAndWait();
            } catch (Exception e) {
                System.out.println("=== 关于 JavaFX Demo ===");
                System.out.println("版本: 1.0");
                System.out.println("作者: dragon");
                System.out.println("描述: 一个支持系统托盘的JavaFX演示应用程序");
                System.out.println("=======================");
            }
        });
    }

    /**
     * 备用退出方法（当主退出服务不可用时使用）
     */
    private void fallbackExit() {
        new Thread(() -> {
            try {
                System.out.println("使用备用退出方法...");
                if (primaryStage != null) {
                    Platform.runLater(() -> primaryStage.close());
                }
                cleanup();
                Thread.sleep(300);
                Platform.runLater(Platform::exit);
                Thread.sleep(200);
                System.exit(0);
            } catch (Exception ex) {
                System.err.println("备用退出失败: " + ex.getMessage());
                System.exit(1);
            }
        }).start();
    }

    /**
     * 清理托盘资源
     */
    @PreDestroy
    public void cleanup() {
        if (systemTray != null && trayIcon != null) {
            systemTray.remove(trayIcon);
        }
    }

    /**
     * 检查托盘是否已初始化
     */
    public boolean isTrayInitialized() {
        return trayIcon != null && systemTray != null;
    }

    /**
     * 显示托盘消息
     */
    public void showTrayMessage(String title, String message, TrayIcon.MessageType messageType) {
        if (trayIcon != null) {
            trayIcon.displayMessage(title, message, messageType);
        }
    }
}